package main

import (
	"backend/internal/common/errorx"
	"backend/internal/core/modbus_client"
	"backend/internal/db/model"
	"errors"
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"os"
	"path/filepath"

	"backend/internal/config"
	"backend/internal/handler"
	"backend/internal/svc"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
)

// 获取配置文件的路径
func getConfigFilePath() string {
	// 优先尝试从项目根目录的etc文件夹查找
	if _, err := os.Stat("etc/modbusServer.yaml"); err == nil {
		return "etc/modbusServer.yaml"
	}

	// 如果不存在，再尝试从可执行文件所在目录查找
	exePath, err := os.Executable()
	if err != nil {
		return "etc/modbusServer.yaml"
	}
	exeDir := filepath.Dir(exePath)
	return filepath.Join(exeDir, "etc", "modbusServer.yaml")
}

var configFile = flag.String("f", getConfigFilePath(), "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	logx.MustSetup(c.Log)                     // 设置日志配置
	logx.AddWriter(logx.NewWriter(os.Stdout)) // 添加控制台输出

	clientManager := modbus_client.NewClientManager()
	defer clientManager.ClearAllClients()

	server := rest.MustNewServer(c.RestConf, rest.WithCors())
	defer server.Stop()

	ctx := svc.NewServiceContext(c, clientManager)
	handler.RegisterHandlers(server, ctx)

	// 从数据库获取设备列表并创建对应的 Modbus 客户端
	var devices []model.Device
	if err := ctx.GormDB.Find(&devices).Error; err != nil {
		errorStr := fmt.Sprintf("查询设备列表失败: %v", err)
		logx.Errorf(errorStr)
	}
	clientManager.SetAllClient(devices)

	// 自定义错误
	httpx.SetErrorHandler(func(err error) (int, interface{}) {
		var e *errorx.CodeError
		switch {
		case errors.As(err, &e):
			return http.StatusOK, e.Data()
		default:
			return http.StatusOK, &errorx.CodeErrorResponse{
				Status:  errorx.DefaultCode,
				Message: err.Error(), // 使用 err.Error() 获取错误信息
			}
		}
	})

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
